package edu.hcp.longshorturl.utils;



/**                                                                                ____________________
      _                _                                                           < 神兽护体，永无bug! >
    | |__  _   _  ___| |__   ___ _ __   __ _ _ __   ___ _ __   __ _                --------------------
   | '_ \| | | |/ __| '_ \ / _ \ '_ \ / _` | '_ \ / _ \ '_ \ / _` |                       \   ^__^
  | | | | |_| | (__| | | |  __/ | | | (_| | |_) |  __/ | | | (_| |                        \  (oo)\_______
 |_| |_|\__,_|\___|_| |_|\___|_| |_|\__, | .__/ \___|_| |_|\__, |                           (__)\       )\/\
                                   |___/|_|                |___/                                ||----w |
                                                                                                ||     ||
 * @author huchengpeng
 * @date 2021/8/21 19:27
 * @version
 * @Description
 */
public class UrlUtils {

    static final String str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    static final int MAX_LEN = 6;

    /**
     * 算法二：随机生成ShortUrl + 数据库去重
     * 伪代码
     */
//    private String longToShort(String longUrl){
//        while(true){
//            String shortUrl = UUID.randomUUID().toString().replaceAll("-","");
//            UrlEntity urlEntity = urlMapper.selectByShortUrl(shortUrl);
//            if(urlEntity != null){
//                // 有重复
//                continue;
//            }
//            // 没重复，直接插入
//            urlMapper.insertShortUrl(shortUrl,longUrl);
//        }
//    }

    /**
     * 算法三：进制转换 Base62
     */

    /**
     * id 转 shortUrl
     * @param shortUrl 短网址
     * @return 短网址对应的 id
     */
    public static long shortUrlToId(String shortUrl){
        long id = 0;
        char[] chars = shortUrl.toCharArray();
        for(int i=0;i < chars.length; i++){
            id = id * 62 + toBase62(chars[i]);
        }
        return id;
    }

    private static int toBase62(char ch){
        return str.indexOf(ch);
    }

    /**
     * id 转 短网址
     * @param id id
     * @return id 对应的短网址
     */
    public static String idToShortUrl(Long id){
        StringBuilder shortUrl = new StringBuilder();
        while ( id > 0){
            shortUrl.append(str.charAt((int)(id % 62)));
            id /= 62;
        }
        while(shortUrl.length() < MAX_LEN){
            shortUrl.append("0");
        }
        return shortUrl.reverse().toString();
    }

}
